<script setup lang="ts">
import VDialog from "@/components/VDialog/VDialog.vue";
import { computed, reactive, ref } from "vue";
import {
  AddBotQuestionCommand,
  BotQuestionPageResponse,
  UpdateBotQuestionCommand,
  addBotQuestionApi,
  updateBotQuestionApi
} from "@/api/bot/bot-question";
import { ElMessage, FormInstance, FormRules } from "element-plus";

interface Props {
  type: "add" | "update";
  modelValue: boolean;
  row?: BotQuestionPageResponse;
}

const props = defineProps<Props>();
const emits = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
  (e: "success"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set(v) {
    emits("update:modelValue", v);
  }
});

const formData = reactive<AddBotQuestionCommand | UpdateBotQuestionCommand>({
  id: 0,
  question: "",
  answer: "",
  createUser: ""
});

const rules: FormRules = {
  question: [
    {
      required: true,
      message: "问题不能为空"
    }
  ],
  answer: [
    {
      required: true,
      message: "答案不能为空"
    }
  ]
};

const formRef = ref<FormInstance>();
function handleOpened() {
  if (props.row) {
    Object.assign(formData, props.row);
  } else {
    formRef.value?.resetFields();
  }
}

const loading = ref(false);
async function handleConfirm() {
  try {
    loading.value = true;
    if (props.type === "add") {
      await addBotQuestionApi(formData);
    } else if (props.type === "update") {
      await updateBotQuestionApi(formData as UpdateBotQuestionCommand);
    }
    ElMessage.info("提交成功");
    visible.value = false;
    emits("success");
  } catch (e) {
    console.error(e);
    ElMessage.error((e as Error)?.message || "提交失败");
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <v-dialog
    show-full-screen
    :fixed-body-height="false"
    use-body-scrolling
    :title="type === 'add' ? '新增问答' : '更新问答'"
    v-model="visible"
    :loading="loading"
    @confirm="handleConfirm"
    @cancel="visible = false"
    @opened="handleOpened"
  >
    <el-form :model="formData" label-width="120px" :rules="rules" ref="formRef">
      <el-form-item prop="question" label="问题" required inline-message>
        <el-input v-model="formData.question" />
      </el-form-item>
      <el-form-item prop="answer" label="答案" required>
        <el-input type="textarea" v-model="formData.answer" rows="6" />
      </el-form-item>
      <el-form-item prop="createUser" label="创建人">
        <el-input v-model="formData.createUser" />
      </el-form-item>
    </el-form>
  </v-dialog>
</template>
